package org.jeecg.modules.qyxx.service.impl;


import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;
import org.jeecg.modules.fk.entity.DjOrg;
import org.jeecg.modules.qyxx.entity.CjQyxxStatus;
import org.jeecg.modules.qyxx.mapper.CjQyxxStatusMapper;
import org.jeecg.modules.qyxx.service.ICjQyxxStatusService;
import org.jeecg.modules.qyxx.util.DateUtils;
import org.jeecg.modules.qyxx.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Description: 采集企业信息结果
 * @Author: ZJJ
 * @Date: 2021-06-11
 * @Version: V1.0
 */
// @DS("multi-datasource1")申报
@Service
public class CjQyxxStatusServiceImpl extends MppServiceImpl<CjQyxxStatusMapper, CjQyxxStatus> implements ICjQyxxStatusService {
    private static final String CJ_FP_STATUS_KEY = "cjFpStatus";
    // fplx_dm 进项发票- jxfp  销项发票- xxfp
    private static final String JXFP = "jxfp";
    private static final String XXFP = "xxfp";


    @Override
    public Integer getCjInfo(String djxh, String ssny) {
        // System.out.println(djxh);
        LambdaQueryWrapper<CjQyxxStatus> wrapper = Wrappers.lambdaQuery(CjQyxxStatus.class);
        //String str = ssny.substring(0,4) + "-" + ssny.substring(4,6) + "-01 00:00:00";
        //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //try {
        //Date date = simpleDateFormat.parse(str);
        wrapper.eq(CjQyxxStatus::getDjxh, djxh).le(CjQyxxStatus::getKssj, ssny).ge(CjQyxxStatus::getJssj, ssny);
        return baseMapper.selectCount(wrapper);
       /* } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;*/
    }

    @Override
    public void recordFpCompleteStatus(String fplx, DjOrg org, Date kssj, Date jssj) {
        boolean flag = RedisUtil.hasKey(CJ_FP_STATUS_KEY + fplx + org.getShxydm() + kssj.toString() + jssj.toString());
        if (flag) {
            return;
        }
        LambdaQueryWrapper<CjQyxxStatus> query = Wrappers.lambdaQuery(CjQyxxStatus.class);
        query.eq(CjQyxxStatus::getDjxh, org.getShxydm()).eq(CjQyxxStatus::getKssj, kssj).eq(CjQyxxStatus::getJssj, jssj);
        CjQyxxStatus one = super.getOne(query);
        if (one == null) {
            CjQyxxStatus cjQyxxStatus = new CjQyxxStatus();
            cjQyxxStatus.setKssj(kssj);
            cjQyxxStatus.setJssj(jssj);
            cjQyxxStatus.setDjxh(org.getShxydm());
            cjQyxxStatus.setNsrsbh(org.getShxydm());
            cjQyxxStatus.setNsrmc(org.getNsrmc());
            cjQyxxStatus.setType("04");
            cjQyxxStatus.setCreateTime(new Date());
            cjQyxxStatus.setStatus("0");
            cjQyxxStatus.setUpdateTime(new Date());
            super.save(cjQyxxStatus);
            RedisUtil.set(CJ_FP_STATUS_KEY + fplx + org.getShxydm() + kssj.toString() + jssj.toString(), CJ_FP_STATUS_KEY + fplx + "complete");
        } else {
            LambdaUpdateWrapper<CjQyxxStatus> update = Wrappers.lambdaUpdate(CjQyxxStatus.class);
            update.eq(CjQyxxStatus::getDjxh, org.getShxydm()).eq(CjQyxxStatus::getKssj, kssj).eq(CjQyxxStatus::getJssj, jssj)
                    .set(CjQyxxStatus::getStatus, "1").set(CjQyxxStatus::getUpdateTime, new Date());
            super.update(update);
            RedisUtil.del(CJ_FP_STATUS_KEY + JXFP + org.getShxydm() + kssj.toString() + jssj.toString(), CJ_FP_STATUS_KEY + XXFP + org.getShxydm() + kssj.toString() + jssj.toString());
        }
    }

    /**
     * 初始化首化采集数据，应该在授权成功的时候调用
     *
     * @param org
     * @param force
     */
    @Override
    public void initFirstTimeCjStatus(DjOrg org, boolean force) {
        //业务域类型（01-基本信息【纳税基本信息，纳税人扩展信息】 02-财务报表【利润表、资产负债表、现金流量表】 03-申报纳税【应缴税费表、未缴纳清册】 04-增值税发票【进项发票明细表、销售发票明细表】）
        //计算出起止日期
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -1);
        int year = cal.get(Calendar.YEAR);
        //上月的最后一天
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.set(year - 4, 0, 1, 00, 00, 00);
        cal.set(Calendar.DATE, lastDay);


        DateUtils dateUtils = DateUtils.getInstance();
        String start = dateUtils.DatetoStr(startCalendar.getTime(), "yyyy-MM-dd");
        String end = dateUtils.DatetoStr(cal.getTime(), "yyyy-MM-dd");
        Date kssj = dateUtils.strToDate(start, "yyyy-MM-dd");
        Date jssj = dateUtils.strToDate(end, "yyyy-MM-dd");
        //01-基本信息【纳税基本信息，纳税人扩展信息】 基本信息在授权的时候已经完成
        LambdaQueryWrapper<CjQyxxStatus> jbxxWrapper = new LambdaQueryWrapper<>();
        jbxxWrapper.eq(CjQyxxStatus::getDjxh, org.getDjxh());
        jbxxWrapper.eq(CjQyxxStatus::getType, "01");
        int countJbxx = this.count(jbxxWrapper);
        if (countJbxx == 0 || force == true) {
            CjQyxxStatus jbxxcj = new CjQyxxStatus()
                    .setDjxh(org.getDjxh())
                    .setNsrsbh(org.getDjxh())
                    .setNsrmc(org.getNsrmc())
                    .setKssj(kssj)
                    .setJssj(jssj)
                    .setType("01")
                    .setStatus("0");
            this.saveOrUpdateByMultiId(jbxxcj);
        }

        LambdaQueryWrapper<CjQyxxStatus> cwxxWrapper = new LambdaQueryWrapper<>();
        cwxxWrapper.eq(CjQyxxStatus::getDjxh, org.getDjxh());
        cwxxWrapper.eq(CjQyxxStatus::getType, "02");
        int countCwxx = this.count(cwxxWrapper);
        if (countCwxx == 0 || force == true) {
            //02-财务报表【利润表、资产负债表、现金流量表】
            CjQyxxStatus cbxxcj = new CjQyxxStatus()
                    .setDjxh(org.getDjxh())
                    .setNsrsbh(org.getDjxh())
                    .setNsrmc(org.getNsrmc())
                    .setKssj(kssj)
                    .setJssj(jssj)
                    .setType("02")
                    .setStatus("0");
            this.saveOrUpdateByMultiId(cbxxcj);
        }
        //03-申报纳税【应缴税费表、未缴纳清册】
        LambdaQueryWrapper<CjQyxxStatus> sbxxWrapper = new LambdaQueryWrapper<>();
        sbxxWrapper.eq(CjQyxxStatus::getDjxh, org.getDjxh());
        sbxxWrapper.eq(CjQyxxStatus::getType, "03");
        int countSbxx = this.count(sbxxWrapper);
        if (countSbxx == 0 || force == true) {
            CjQyxxStatus sbxxcj = new CjQyxxStatus()
                    .setDjxh(org.getDjxh())
                    .setNsrsbh(org.getDjxh())
                    .setNsrmc(org.getNsrmc())
                    .setKssj(kssj)
                    .setJssj(jssj)
                    .setType("03")
                    .setStatus("0");
            this.saveOrUpdateByMultiId(sbxxcj);
        }

/*        //04-增值税发票【进项发票明细表、销售发票明细表】
        LambdaQueryWrapper<CjQyxxStatus> fpxxWrapper = new LambdaQueryWrapper<>();
        fpxxWrapper.eq(CjQyxxStatus::getDjxh, org.getDjxh());
        fpxxWrapper.eq(CjQyxxStatus::getType, "04");
        int countFpxx = this.count(cwxxWrapper);
        if (countFpxx == 0 || force == true) {
            CjQyxxStatus fpxxcj = new CjQyxxStatus()
                    .setDjxh(org.getDjxh())
                    .setNsrsbh(org.getDjxh())
                    .setNsrmc(org.getNsrmc())
                    .setKssj(startCalendar.getTime())
                    .setType("04")
                    .setStatus("0");
            this.saveOrUpdateByMultiId(fpxxcj);
        }*/
    }

    /**
     * 初始化每月需要采集数据的企业
     *
     * @param start
     * @param end
     */
    @Override
    public void initBatchMonthCjStatus(Date start, Date end) {
        //不用处理发票
        List<String> types = Arrays.asList("01", "02", "03");
        for (String type : types) {
            baseMapper.initBatchMonthCjStatus(type, start, end);
        }
    }

    @Override
    public List<DjOrg> getNeedFirstInitOrgList() {
        return baseMapper.getNeedFirstInitOrgList();
    }
}
